<template>
  <div class="layout-route">
        <div class="card card-search">
                <el-form :model="queryParams" ref="queryForm" v-show="showSearch" inline label-width="100px">
                    <el-form-item label="广告ID" prop="advertiser_id">
                        <el-input v-model.trim="queryParams.advertiser_id" placeholder="请输入广告ID" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
                    </el-form-item>

                    <el-form-item label="运营" prop="admin_id">
                        <el-select v-model="queryParams.admin_id" placeholder="请选择运营" clearable size="small" style="width: 240px">
                            <el-option v-for="(dict, index) in salesmanList" :key="index" :label="dict.nickname" :value="dict.id" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="店铺" prop="shop_id">
                        <el-select v-model="queryParams.shop_id" placeholder="请选择店铺" clearable size="small" style="width: 240px">
                            <el-option v-for="(dict, index) in shopList" :key="index" :label="dict.shop_name" :value="dict.shop_id" />
                        </el-select>
                    </el-form-item>

                    
                    <el-form-item label="开始时间" prop="createtime">
                        <el-date-picker v-model="queryParams.createtime" format="yyyy-MM-dd" type="date" start-placeholder="开始时间" end-placeholder="结束时间" style="width: 240px"></el-date-picker>
                    </el-form-item>

                    <el-form-item label=" ">
                        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
      <div class="card">
          <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="el-icon-plus" @click="showDetailDialog">添加</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="warning" plain icon="el-icon-download" :loading="download" @click="handleExport">导出</el-button>
                </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
          <el-table v-loading="loading" :data="tableData" border script>
              <el-table-column label="广告ID" prop="advertiser_id" min-width="200" show-overflow-tooltip>
                <template slot-scope="scope">
                    <el-select v-model="scope.row.advertiser_id" placeholder="请选择" clearable size="small" filterable @change="chooseItem(scope.row)">
                        <el-option v-for="item in advertiserList" :key="item.id" :label="item.advertiser_id" :value="item.advertiser_id">
                            <span style="float: left">{{ item.advertiser_name }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.advertiser_id }}</span>
                        </el-option>
                    </el-select>
                </template>
              </el-table-column>
              <el-table-column label="归属人" prop="admin_name" min-width="200" show-overflow-tooltip>
                <template slot-scope="scope">
                    <el-select v-model="scope.row.admin_name" placeholder="请选择" clearable size="small" filterable @change="chooseItem(scope.row)">
                        <el-option v-for="item in onSaleList" :key="item.id" :label="item.nickname" :value="item.id">
                            <span style="float: left">{{ item.nickname }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
                        </el-option>
                    </el-select>
                </template>
              </el-table-column>
              <el-table-column label="店铺" prop="shop_name" min-width="200" show-overflow-tooltip>
                <template slot-scope="scope">
                    <el-select v-model="scope.row.shop_id" placeholder="请选择" clearable size="small" filterable @change="chooseItem(scope.row)">
                        <el-option v-for="item in shopList" :key="item.shop_id" :label="item.shop_name" :value="item.shop_id">
                            <span style="float: left">{{ item.shop_name }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.shop_id }}</span>
                        </el-option>
                    </el-select>
                </template>
              </el-table-column>
              <el-table-column label="归属开始时间" prop="createtime" min-width="200">
                <template slot-scope="scope">   
                    <el-date-picker v-model="scope.row.createtime" type="date" value-format="yyyy-MM-dd" placeholder="请选择" clearable  @change="chooseItem(scope.row)"> </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column label="归属结束时间" prop="updatetime" min-width="200">
                <template slot-scope="scope">   
                    <el-date-picker v-model="scope.row.updatetime" type="date" value-format="yyyy-MM-dd" placeholder="请选择" clearable  @change="chooseItem(scope.row)"> </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column label="状态" prop="status" min-width="60">
                  <template slot-scope="scope">
                      {{ scope.row.status | formatLabelByValueFuzzy(STATUS_LIST) }}
                  </template>
              </el-table-column>
              <el-table-column label="操作" prop="status" min-width="120" fixed="right">
                  <template slot-scope="scope">
                    <el-button type="text" @click="deleteItem(scope.row, scope.$index)" :disabled="loadingDelete">删除</el-button>
                  </template>
              </el-table-column>
          </el-table>
          <pagination v-show="total > 0" :total="total" :page.sync="pageInfo.page" :limit.sync="pageInfo.limit" @pagination="getList"></pagination>
      </div>
      <detail-dialog v-model="detailDialog.visible" v-if="detailDialog.visible" :params="detailDialog.data" :type="detailDialog.type" @success="handleQuery"></detail-dialog>
  </div>
</template>

<script>
import { exportFile } from '@/utils/index'
import { queryAscriptionList,exportAscription, editAscription, deleteAscription, getAdvistementList } from '@/api/advertisement'
import { getShopList, getSalesmanList, getOnSalesList } from '@/api/shop'
import { STATUS_LIST } from '../constant'
import DetailDialog from './components/DetailDialog.vue'
export default {
  name: 'SupplyList',
  components: { DetailDialog },
  data() {
      return {
          // 遮罩层
          loading: true,
          loadingDelete: false,
          // 显示搜索条件
          showSearch: true,
          // 总条数
          total: 0,
          // 表格数据
          tableData: [],
          STATUS_LIST,
          pageInfo: {
              page: 1,
              limit: 10,
          },
        // 店铺列表下拉
        shopList: [],
        salesmanList: [],
        onSaleList: [],
        advertiserList: [],
        download: false,
        // 查询参数
        queryParams: {
            shop_id: undefined,
            admin_id: undefined,
            advertiser_id: undefined,
            platform_id: undefined,
        },
        detailDialog: {
            visible: false,
            data: {},
        },
      }
  },
  watch: {
    '$route': {
      handler(val) {
        this.queryParams.advertiser_id =val.query.advertiser_id
      },
      immediate: true
    }
  },

    async created() {
            this.loading = true
            try {
                this.loading = true;
                const [shopData, salesmanData, onSaleData, accountData] = await Promise.all([getShopList(), getSalesmanList(), getOnSalesList(), getAdvistementList()]);
                this.shopList = shopData?.data?.list ?? [];
                this.salesmanList = salesmanData?.data?.list ?? [];
                this.onSaleList= onSaleData?.data ?? [];
                this.advertiserList = accountData?.data ?? [];
            } catch (error) {
                this.loading = false;
                // 可以根据实际情况添加错误处理逻辑，例如显示错误消息给用户
                console.error('Failed to fetch shop and salesman data:', error);
            }
            this.getList();
        },
  methods: {
        handleExport() {
            this.download = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
            if (qyparams.createtime?.length == 2) {
                qyparams.createtime = [parseTime(qyparams.createtime[0], 'y-m-d'), parseTime(qyparams.createtime[1], 'y-m-d')]
            }
            exportAscription(qyparams)
                .then(res => {
                    exportFile(res, () => {
                        this.download = false
                    })
                })
                .catch(err => {
                    this.download = false
                })
        },
    deleteItem(item, index){
            this.$confirm(`是否确认删除?`, '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.loadingDelete = true
                deleteAscription(item).then(res=>{
                    this.$message.success(res.msg)
                    this.resetQuery()
                }).finally(()=>{
                    this.loadingDelete = false
                })
            }).catch(() => { })
        },
    showDetailDialog() {
        this.detailDialog.visible = true
    },
    chooseItem(row) {
        editAscription(row).then((res)=>{
                this.$message.success(res.msg)
                this.resetQuery()
            })
        },
      //列表
      getList() {
          this.loading = true
          const qyparams = {
              ...this.pageInfo,
              ...this.queryParams,
          }
          queryAscriptionList(qyparams)
              .then(response => {
                  this.tableData = response.data.list.map((item)=>{
                    if(item.updatetime == '至今') {
                        item.updatetime = new Date()
                    }
                    return {...item}
                  })
                  this.total = response.data.total
              })
              .finally(() => {
                  this.loading = false
              })
      },

      // 搜索按钮操作
      handleQuery() {
          this.pageInfo.page = 1
          this.getList()
      },

      // 重置按钮操作
      resetQuery() {
          this.resetForm('queryForm')

          this.handleQuery()
      },
  },
}
</script>
